var app = getApp();
Component({
  properties: {
    // 提交状态
    status: {
      type: null
    },
    // 表单数据
    field: {
      type: null
    },
    useActionSlot:{
      type: null,
      value: false
    },
    thumb: {
      type: null
    },
    description: {
      type: null
    },
  },
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  data: {
    imgPath: app.globalData.imgPath,
    click: false,
    startDate: new Date("1900-01-01"),
    Height: "",
    formList: [],
    showAddress: false,
    form_id: "",
    shoTime: "",
    types: {
      88: "diyusername",
      99: "diypassword",
      0: "diyinput",
      1: "diytextarea",
      3: "diycheckbox",
      4: "diyradio",
      2: "diyselect",
      7: "diydate",
      9: "diycity",
      5: "diyimage",
    },
    diydata: [],
    setname: "",
    // uploadUrl: 'plugin.diyform.api.diy-form.DiyFormUpload',
    uploadUrl: "upload.uploadPic",
    //地区
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    currentDate: new Date().getTime(),
    showCity1: false,
  }, // 私有数据，可用于模板渲染

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {},
    moved() {},
    detached() {},
  },
  observers: {
    // 'isTag': function (str) {
    //   this.setData({
    //     aisTag: str
    //   });
    // }
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {}, // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    if (this.data.status == 0 && Object.keys(this.data.field).length != 0) this.getDiyFormSingData(this.data.field); //未提交表单，可编辑状态
    if (this.data.status == 1 && Object.keys(this.data.field).length != 0) this.getDiyFormSingDataFalse(this.data.field);
    this._initAddressInfo();
  },
  methods: {
    getDiyFormSingData(fields) {
      let that = this;
      let diydata = [];
      let f = null;
      for (var field in fields) {
        if (fields[field].data_type == 7) {
          console.log(fields[field].default_time);
          var timestamp = Date.parse(new Date());
          var date = new Date(timestamp);
          //获取年份
          var Y = date.getFullYear();
          //获取月份
          var M =
            date.getMonth() + 1 < 10 ?
              "0" + (date.getMonth() + 1) :
              date.getMonth() + 1;
          //获取当日日期
          var D =
            date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
          console.log(Y + "-" + M + "-" + D);
          var isdatae = Y + "-" + M + "-" + D;
          f = {
            name: field,
            data: fields[field],
            value: fields[field].default_time,
            type: that.data.types[fields[field].data_type],
          };
        }
        if (that.data.types[fields[field].data_type] == "diycheckbox") {
          f = {
            name: field,
            data: fields[field],
            value: fields[field].value ? fields[field].value : [],
            type: that.data.types[fields[field].data_type],
          };
        } else if (
          that.data.types[fields[field].data_type] == "diydate"
        ) {
          f = {
            name: field,
            data: fields[field],
            value: fields[field].value ? fields[field].value : "",
            type: that.data.types[fields[field].data_type],
            timeShow: false,
            currentDate: new Date().getTime(),
            shoTime: fields[field].default_time ?
              fields[field].default_time :
              isdatae,
          };
        } else if (
          that.data.types[fields[field].data_type] == "diyselect"
        ) {
          let tp_textArr = [];
          for (let i = 0; i < fields[field].tp_text.length; i++) {
            tp_textArr.push({
              name: fields[field].tp_text[i],
            });
          }
          f = {
            name: field,
            data: fields[field],
            value: fields[field].value ? fields[field].value : "",
            type: that.data.types[fields[field].data_type],
            diysishow: false,
            sitem: tp_textArr,
          };
        } else if (
          that.data.types[fields[field].data_type] == "diycity"
        ) {
          f = {
            name: field,
            data: fields[field],
            value: fields[field].value ? fields[field].value : "",
            type: that.data.types[fields[field].data_type],
            showAdd: false,
          };
        } else if (
          that.data.types[fields[field].data_type] == "diyimage" || that.data.types[fields[field].data_type] == "5"
        ) {
          f = {
            name: field,
            data: fields[field],
            imgUrls: fields[field].value ? fields[field].value : [],
            isPhoto: false,
            type: that.data.types[fields[field].data_type],
          };
        } else {
          f = {
            name: field,
            data: fields[field],
            value: fields[field].value ? fields[field].value : "",
            type: that.data.types[fields[field].data_type],
          };
        }
        diydata.push(f);
        that.setData({
          diydata: diydata,
        });
      }
    },
    getDiyFormSingDataFalse(fields) {
      let that = this;
      for (let field in fields) {
        var list = {
          title: fields[field].tp_name,
          value: fields[field].value,
          data_type: fields[field].data_type,
          tp_must: fields[field].tp_must,
        };
        if (list.data_type == "3") {
          list.value = fields[field].value.join(",");
        }
        if (list.data_type == "7") {
          list.value = fields[field].value;
        }
        if (list.data_type == "1") {
          list.value = fields[field].value;
        }
        that.data.formList.push(list);
        that.setData({
          formList: that.data.formList,
        });
      }
    },
    //获取表单信息
    getForm() {
      let that = this;
      let urlStr = "";

      if (that.data.modeType == "member") {
        urlStr = app.getNetAddresss(
          "plugin.diyform.api.diy-form.getDiyFormTypeMemberData"
        );
        urlStr += "&form_id=" + this.data.datas;
      } else {
        urlStr = app.getNetAddresss(
          "plugin.diyform.api.diy-form.getSingleFormData"
        );
        if (this.data.datas.diyform_data_id) {
          urlStr += "&form_data_id=" + this.data.datas.diyform_data_id;
        }
        if (this.data.form_data_id) {
          urlStr += "&form_data_id=" + this.data.form_data_id;
        }
        urlStr += "&form_id=" + this.data.datas.form_id;
      }


      app._postNetWork({
        url: urlStr,
        data: {
          not_validate_page: '0'
        },
        success: function (resdata) {
          var res = resdata.data;
          console.log(res.data, '12211');
          if (res.result == 1) {
            if (app._isTextEmpty(res.data.thumb)) {
              that.setData({
                thumb: false,
              });
            } else {
              that.setData({
                thumb: res.data.thumb,
              });
            }
            if (app._isTextEmpty(res.data.description)) {
              that.setData({
                description: false,
              });
            } else {
              that.setData({
                description: res.data.description,
              });
            }
            if (that.data.params !== "order") {
              wx.setNavigationBarTitle({
                title: res.data.title,
              });
              that.setData({
                status: res.data.status,
                loading: true,
              });
            } else {
              that.setData({
                status: 0,
                loading: true,
              });
            }
            console.log(that.data.params, that.data.status, '173');
            if (that.data.status === 1) {
              that.setData({
                diyform: res.data,
                thumb: res.data.thumb,
              });
              const fields = that.data.diyform.fields;
              for (let field in fields) {
                var list = {
                  title: fields[field].tp_name,
                  value: fields[field].value,
                  data_type: fields[field].data_type,
                  tp_must: fields[field].tp_must,
                };
                if (list.data_type == "3") {
                  list.value = fields[field].value.join(",");
                }
                if (list.data_type == "7") {
                  list.value = fields[field].value;
                }
                if (list.data_type == "1") {
                  list.value = fields[field].value;
                }
                that.data.formList.push(list);
                that.setData({
                  formList: that.data.formList,
                });
              }
            } else {
              that.setData({
                diyform: res.data,
              });
              let fields = that.data.diyform.fields;
              let diydata = that.data.diydata;
              let f = null;
              for (var field in fields) {
                if (fields[field].data_type == 7) {
                  console.log(fields[field].default_time);
                  var timestamp = Date.parse(new Date());
                  var date = new Date(timestamp);
                  //获取年份
                  var Y = date.getFullYear();
                  //获取月份
                  var M =
                    date.getMonth() + 1 < 10 ?
                      "0" + (date.getMonth() + 1) :
                      date.getMonth() + 1;
                  //获取当日日期
                  var D =
                    date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                  console.log(Y + "-" + M + "-" + D);
                  var isdatae = Y + "-" + M + "-" + D;
                  f = {
                    name: field,
                    data: fields[field],
                    value: fields[field].default_time,
                    type: that.data.types[fields[field].data_type],
                  };
                }
                if (that.data.types[fields[field].data_type] == "diycheckbox") {
                  f = {
                    name: field,
                    data: fields[field],
                    value: fields[field].value ? fields[field].value : [],
                    type: that.data.types[fields[field].data_type],
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diydate"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    value: fields[field].value ? fields[field].value : "",
                    type: that.data.types[fields[field].data_type],
                    timeShow: false,
                    currentDate: new Date().getTime(),
                    shoTime: fields[field].default_time ?
                      fields[field].default_time :
                      isdatae,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diyselect"
                ) {
                  let tp_textArr = [];
                  for (let i = 0; i < fields[field].tp_text.length; i++) {
                    tp_textArr.push({
                      name: fields[field].tp_text[i],
                    });
                  }
                  f = {
                    name: field,
                    data: fields[field],
                    value: fields[field].value ? fields[field].value : "",
                    type: that.data.types[fields[field].data_type],
                    diysishow: false,
                    sitem: tp_textArr,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diycity"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    value: fields[field].value ? fields[field].value : "",
                    type: that.data.types[fields[field].data_type],
                    showAdd: false,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diyimage"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    imgUrls: fields[field].value ? fields[field].value : [],
                    isPhoto: false,
                    type: that.data.types[fields[field].data_type],
                  };
                } else {
                  f = {
                    name: field,
                    data: fields[field],
                    value: fields[field].value ? fields[field].value : "",
                    type: that.data.types[fields[field].data_type],
                  };
                }
                diydata.push(f);
                that.setData({
                  diydata: diydata,
                });
              }
            }
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //自定义表单值绑定
    tpnameinp(e) {
      let val = e.detail.value;
      let idx = e.currentTarget.dataset.idex;

      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },

    update() {
      var that = this;
      var formData = [];
      var formObject = {};
      this.data.diydata.forEach(item => {
        if (item.type == "diyimg") {
          var arr = [];
          for (let i = 0; i < item[item.name + "Value1"].length; i++) {
            arr.push(item[item.name + "Value1"][i].url);
          }
          formObject[item.name] = arr;
        } else {
          formObject[item.name] = item.value;
        }
      });
      if (!app._isTextEmpty(that.data.form_data_id)) {
        var json = {
          form_data: formData,
          form_data_id: that.data.form_data_id
        };
      }
      formData.push(formObject);
      console.log(json);
    },
    onRead_1(e) {
      try {
        let diydata = this.data.diydata;
        let ind = e.currentTarget.dataset.idex;
        if (diydata[ind].imgUrls.length >= diydata[ind].data.tp_max) {
          wx.showToast({
            title: `最多只能上传${diydata[ind].data.tp_max}张`,
            icon: "none",
            duration: 1000,
          });
          return;
        }
      } catch (err) {
        console.log(err);
      }
      let name = e.currentTarget.dataset.name;
      this.setData({
        setname: name,
      });
      let that = this;
      let urlStr = app.getNetAddresss(this.data.uploadUrl);
      wx.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          wx.compressImage({
            src: tempFilePaths[0], // 图片路径
            quality: 60, // 压缩质量
            success(e) {
              let photourl = e.tempFilePath;
              wx.uploadFile({
                url: urlStr,
                filePath: photourl,
                name: "file",
                formData: {
                  attach: that.data.setname,
                },
                success(resdata) {
                  var res = JSON.parse(resdata.data);
                  console.log(res);
                  if (res.result == 1) {
                    let diydata = that.data.diydata;
                    for (var i = 0; i < diydata.length; i++) {
                      if (diydata[i].name == res.data.attach) {
                        diydata[i].imgUrls.push(res.data.img_url);
                      }
                    }
                    that.setData({
                      diydata: diydata,
                    });
                  } else {
                    wx.showToast({
                      icon: "none",
                      title: res.msg,
                      duration: 1500,
                    });
                  }
                },
              });
            },
            fail(e) {
              console.log(e);
            },
            complete(e) {},
          });
        },
      });
    },
    removeImg: function (e) {
      let delIndex = e.currentTarget.dataset.indexc;
      let index_1 = e.currentTarget.dataset.index;
      let diydata = this.data.diydata;
      diydata[index_1].imgUrls.splice(delIndex, 1);
      this.setData({
        diydata: diydata,
      });
    },
    diytextareainp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value.value"]: val,
      });
    },
    checkboxinp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    diyselectBtn(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].diysishow"]: true,
      });
    },
    raidinp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    //所在地选择显示
    showAddBtn(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].showAdd"]: true,
      });
    },
    // 关闭选择收货地址
    _closeDateLw: function (e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].showAdd"]: false,
      });
    },
    //地址选择器数据初始化
    _initAddressInfo: function () {
      var that = this;
      var _keyName = "provinceData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          console.log("地址信息准备就绪");
          that._getProvinceData();
        },
        fail: function (res) {
          console.log("省fail");
          app._getNetWork({
            url: app.getNetAddresss("member.member-address.address"),
            success: function (res) {
              var response = res.data;
              var province = response.data.province;
              var city = response.data.city;
              var district = response.data.district;
              wx.setStorage({
                key: "provinceData",
                data: province,
              });
              wx.setStorage({
                key: "cityData",
                data: city,
              });
              wx.setStorage({
                key: "districtData",
                data: district,
              });
              that._initAddressInfo();
            },
            fail: function (res) {},
            state: true,
          });
        },
      });
    },
    // 读取省key
    _getProvinceData: function () {
      var that = this;
      var _keyName = "provinceData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          // console.log("省读取成功", res.data);
          that.setData({
            provinceData: res.data,
          });
          that.setData({
            "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
            "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
            "selectAddressData[0].index": that.data.pickerValue[0],
          });
          that._getCityData();
        },
      });
    },
    // 读取城市key，筛选城市data
    _getCityData: function () {
      var _data = this.data.selectAddressData[0];
      // console.log("城市", "_data", _data);
      var that = this;
      var _keyName = "cityData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          // console.log("城市读取成功", res);

          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          // console.log("城市数据筛选", _json);
          that.setData({
            cityData: _json,
          });
          that.setData({
            "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
            "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
            "selectAddressData[1].index": that.data.pickerValue[1],
          });
          that._getDistrictData();
        },
      });
    },
    // 读取地区key，筛选地区data
    _getDistrictData: function () {
      var _data = this.data.selectAddressData[1];
      // console.log("地区", "_data", _data)
      // console.log(_data);
      var that = this;
      var _keyName = "districtData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          // console.log("地区读取成功");
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          // console.log("地区数据筛选", _json);
          that.setData({
            districtData: _json,
          });
          // console.log("districtData", _json);
          that.setData({
            "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
            "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
            "selectAddressData[2].index": that.data.pickerValue[2],
          });
          // console.log("over", that.data.selectAddressData);
        },
      });
    },
    // 收货地址滚动事件
    bindChange: function (e) {
      var val = e.detail.value;
      if (this.data.pickerValue[0] != val[0]) {
        val[1] = 0;
        val[2] = 0;
      }
      if (this.data.pickerValue[1] != val[1]) {
        val[2] = 0;
      }
      this.setData({
        "pickerValue[0]": val[0],
        "pickerValue[1]": val[1],
        "pickerValue[2]": val[2],
      });
      this._initAddressInfo();
    },
    //城市结果
    resultAdd: function (e) {
      let idx = e.currentTarget.dataset.idex;
      let seleData = this.data.selectAddressData;
      let retCity =
        seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
      this.setData({
        ["diydata[" + idx + "].value"]: retCity,
        ["diydata[" + idx + "].showAdd"]: false,
      });
    },
    //自定义日期选择
    openPicker(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].timeShow"]: true,
      });
    },
    _closeDateLw_1() {
      this.setData({
        showCity1: false,
      });
    },
    resultAdd_1() {
      let seleData = this.data.selectAddressData;
      this.setData({
        "applyModel.province_name": seleData[0].name,
        "applyModel.city_name": seleData[1].name,
        "applyModel.district_name": seleData[2].name,
        fullAddress: seleData[0].name + " " + seleData[1].name + " " + seleData[2].name,
        showCity1: false,
      });
    },
    submit() {
      this.validation();
      if (!this.data.isValidation) {
        return;
      }
      this.submitForm();
    },
    validation() {
      this.setData({
        isValidation: true,
      });
      this.data.diydata.forEach((item) => {
        if (item.data.tp_must == 1 && !item.value && item.type != "diyimage") {
          wx.showToast({
            icon: "none",
            title: item.data.tp_name + "必须填写哦",
            duration: 1500,
          });
          this.setData({
            isValidation: false,
          });
        }
        if (item.data.tp_must == 1 && item.type == "diyimage") {
          if (item.imgUrls.length <= 0) {
            wx.showToast({
              icon: "none",
              title: `必须上传${item.data.tp_name}`,
              duration: 1500,
            });
            this.setData({
              isValidation: false,
            });
          }
        }
        if (
          item.type == "diycheckbox" &&
          item.value.length == 0 &&
          item.data.tp_must == 1
        ) {
          wx.showToast({
            icon: "none",
            title: item.data.tp_name + "必须选择哦",
            duration: 1500,
          });
          this.setData({
            isValidation: false,
          });
        }
        // if(item.type == 'diyselect' && item.data.tp_must == 1){
        //   wx.showToast({
        //     icon: 'none',
        //     title: item.data.tp_name + '必须填写哦',
        //     duration: 1500
        //   })
        //   this.setData({
        //     isValidation: false
        //   })
        // }
      });
    },
    //自定义表单提交
    submitForm() {
      if (this.data.click) {
        return;
      }
      var that = this;
      that.setData({
        click: true,
      });
      setTimeout(() => {
        that.setData({
          click: false,
        });
      }, 5000);
      var formData = [];
      var formObject = {};
      this.data.diydata.forEach((item) => {
        //图片类型的直接提交图片base64的数组到后台，其它直接传值
        if (item.type == "diyimage") {
          formObject[item.name] = item.imgUrls;
        } else {
          formObject[item.name] = item.value;
        }
        if (item.type == "diytextarea") {
          try {
            formObject[item.name] = item.value.value.value;
          } catch (err) {
            console.log(err);
          }
        }
        if (item.type == "diydate") {
          formObject[item.name] = !app._isTextEmpty(item.value) ?
            that.timestampToTime(item.value * 1000) :
            item.shoTime;
        }
      });
      formData.push(formObject);
      this.triggerEvent('submit', formData);
    },
    sitemSelectBtn(e) {
      let val = e.detail.name;
      let idx = e.currentTarget.dataset.index;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
        ["diydata[" + idx + "].diysishow"]: false,
      });
    },
    sitemClose(e) {
      let idx = e.currentTarget.dataset.index;
      this.setData({
        ["diydata[" + idx + "].diysishow"]: false,
      });
    },
    dateClose(e) {
      let index = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + index + "].timeShow"]: false,
      });
    },
    //日期转化
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10 ?
          "0" + (date.getMonth() + 1) :
          date.getMonth() + 1) + "-";
      let D = this.change(date.getDate()) + " ";
      return Y + M + D;
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },
    birthdayconfirm(e, time) {
      let index = e.currentTarget.dataset.idex;
      let val = e.detail;
      this.setData({
        ["diydata[" + index + "].value"]: String(val).substring(0, 10),
        ["diydata[" + index + "].shoTime"]: this.timestampToTime(val),
        ["diydata[" + index + "].timeShow"]: false,
      });
    },
  },
});